python中的paramiko模块普通用户登录切换root

您所在的位置:网站首页 linux root登陆后切用户 python中的paramiko模块普通用户登录切换root

python中的paramiko模块普通用户登录切换root

2024-07-06 18:50| 来源: 网络整理| 查看: 265

服务器有时候不能root登录,有时候就得切换到root 。这里用到了paramiko模块的一个功能 invoke_shell() 理论上这个功能就是模拟切换用户执行命令的过程,代码如下

#!/usr/bin/python3 #coding=utf-8 import paramiko,time private_key = paramiko.RSAKey.from_private_key_file('/root/.ssh/id_rsa') def verification_ssh(host,username,private_key,port,root_pwd,cmd): s=paramiko.SSHClient() s.load_system_host_keys() s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) s.connect(hostname=host,port=int(port),username=username,pkey=private_key) if username != 'root': ssh = s.invoke_shell() time.sleep(0.1) ssh.send('su - \n') buff = '' while not buff.endswith('Password: '): resp = ssh.recv(9999) buff +=resp.decode('gbk') ssh.send(root_pwd) ssh.send('\n') buff = '' while not buff.endswith('# '): resp = ssh.recv(9999) buff +=resp.decode('gbk') ssh.send(cmd) ssh.send('\n') buff = '' while not buff.endswith('# '): resp = ssh.recv(9999) buff +=resp.decode('gbk') s.close() result = buff else: stdin, stdout, stderr = s.exec_command(cmd) result = stdout.read() s.close() return result res = verification_ssh('172.25.16.38','study',private_key,54321,'xxx','whoami')

功能上可以实现了。这个后边会把执行结果返回一个字符串回来。就可以后边的操作了。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3